package com.nku.mason.lucene;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;

import com.nku.mason.lucene.entity.Article;
import com.nku.mason.lucene.util.LuceneUtil;

/**
 * 对Document对象的多字段进行搜索
 * @author Mason
 *
 */
public class TestMutiFieldQuery {
	
	public void mutiFieldQuerySearch(String keyword) throws Exception{
		List<Article> list = new ArrayList<>();
		IndexSearcher indexSearcher = new IndexSearcher(LuceneUtil.getDirectory());
		QueryParser queryParser = new MultiFieldQueryParser(LuceneUtil.getVersion(), new String[]{"title","content"}, LuceneUtil.getAnalyzer());
		Query query = queryParser.parse(keyword);
		TopDocs topDocs = indexSearcher.search(query, 100);
		for(int i=0;i<topDocs.scoreDocs.length;i++){
			int no = topDocs.scoreDocs[i].doc;
			Document document = indexSearcher.doc(no);
			list.add((Article) LuceneUtil.document2JavaBean(document, Article.class));
		}
		indexSearcher.close();
		
		for(Article a:list){
			System.out.println(a);
		}
	}
	
	public static void main(String[] args) throws Exception {
		TestMutiFieldQuery testMutiFieldQuery = new TestMutiFieldQuery();
		testMutiFieldQuery.mutiFieldQuerySearch("开");
	}
}
